package com.darwin.uuas.controller;


import com.darwin.uuas.constant.HttpStatus;
import com.darwin.uuas.entity.LoginUser;
import com.darwin.uuas.exception.ServiceException;
import com.darwin.uuas.vo.AjaxResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author cui.longcan@chinaott.net 2021/8/31
 */
public abstract class BaseController {
    /**
     * 返回成功
     */
    public AjaxResult success() {
        return AjaxResult.success();
    }

    public AjaxResult success(String message) {
        return AjaxResult.success(message);
    }

    public AjaxResult success(Object data) {
        return AjaxResult.success(data);
    }

    public AjaxResult success(String message, Object data) {
        return AjaxResult.success(message, data);
    }


    /**
     * 返回失败消息
     */
    public AjaxResult error() {
        return AjaxResult.error();
    }

    public AjaxResult error(String message) {
        return AjaxResult.error(message);
    }

    public AjaxResult error(String message, Object data) {
        return AjaxResult.error(message, data);
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     **/
    public LoginUser getLoginUser() {
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw ServiceException.builder()
                    .message("获取用户信息异常")
                    .code(HttpStatus.UNAUTHORIZED)
                    .build();
        }
    }
}
